package servlet;

import dao.DaoAlbum;
import dao.DaoTagAlbum;
import entidades.Album;
import entidades.TagAlbum;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.Global;
import util.Upload;
import util.Util;

/**
 *
 * @author Tarde
 */
@WebServlet(name = "ServletCadAlbum", urlPatterns = {"/ServletCadAlbum"})
public class ServletCadAlbum extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String nome = request.getParameter("nome");
        String tags = request.getParameter("tags");
        String imagem = request.getParameter("imagem");
        if (Util.valida(Util.CAMPO_TEXTO, nome) && Util.valida(Util.CAMPO_ARQUIVO, imagem) && Util.valida(Util.CAMPO_TEXTO, tags)) {

            Upload upload = new Upload(getServletContext().getRealPath(Global.albumData_path + "/" + nome));
            List list = upload.processRequest(request);
            Map<String, String> map = upload.getFormValues(list);
            //Cria album e atribui os valores a ela
            Album album = new Album(nome, imagem);

            //Verificar se a tagAlbum existe, e existir adicionar o album a ela, se não criar a tag
            DaoTagAlbum daoTag = new DaoTagAlbum();
            String[] str = tags.split(";");
            for (String tagName : str) {
                tagName.trim();
                List<TagAlbum> l = daoTag.buscaTagNome(tags);
                if (l.isEmpty()) {
                    //Cria tag e adiciona o album a ela
                    TagAlbum tag = new TagAlbum(tagName);
                    tag.addAlbum(album);
                    album.addTag(tag);
                    daoTag.insert(tag);
                } else {
                    //Adiciona o album a tag
                    TagAlbum tag = l.get(0);
                    tag.addAlbum(album);
                    album.addTag(tag);
                    daoTag.update(tag);
                }
            }
            //Salva o album no banco de dados
            new DaoAlbum().insert(album);

            RequestDispatcher rd = request.getRequestDispatcher("admin/homeAdmin.jsp");
            rd.forward(request, response);
        } else {
            request.setAttribute("erro", "Informações Inválidas");
            RequestDispatcher rd = request.getRequestDispatcher("cadAlbum.jsp");
            rd.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
